package com.simple.car.loader.server.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.simple.car.loader.server.manager.impl.BeamManager;
import com.simple.car.loader.server.tools.Server;

public class LinkerService extends Service {

    public Server server;

    private Thread thread;

    public LinkerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        server = (Server) BeamManager.getInstance().lookup(Server.class.getName());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int command = super.onStartCommand(intent, flags, startId);
        if (thread == null) {
            thread = new Thread(() -> {
                try {
                    server.listen();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                    thread = null;
                }
            });
            thread.start();
        }
        return command;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (thread != null) {
            thread.interrupt();
        }
    }
}